<template>
	<view class="xsdd_detail_content">
        <view class="xsdd_detail_form">

            <view class="xsdd_top">
                <view style="color: #fc4a3a;"> {{ !formData.state ? '待审核' : '已审核' }} </view>
                <view style="display: flex; align-items: center;" >
                    <button v-if="!formData.state" hover-class="hover_btn" @click="handleAudit">审核</button>
                    <uni-data-select
                        :localdata="moreRange"
                        @change="changeMore"
                        :clear="false"
                        placeholder="更多"
                    ></uni-data-select>
                </view>
            </view>


            <uni-forms ref="form" :modelValue="formData" label-width="90">
                <uni-row class="form_row">
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="单据编号:" name="dh">
                            <input type="text" disabled v-model="formData.dh" placeholder="请输入单据编号" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="单据时间:" name="zhdate">
                            <uni-datetime-picker disabled type="date" :clear-icon="false" v-model="formData.zhdate" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="交货日期:" name="jh_date">
                            <uni-datetime-picker :disabled="showEdit" type="date" :clear-icon="false" v-model="formData.jh_date" />
                        </uni-forms-item>
                    </uni-col>
                </uni-row>

                <uni-row class="form_row">
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="客户:" name="khname">
                            <input type="text" disabled v-model="formData.khname" placeholder="请输入客户" />
                        </uni-forms-item>
                    </uni-col>
                  
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="托运方式:" name="tyfs">
                            <uni-data-select
                                class="form_input"
                                v-model="formData.tyfs"
                                :disabled="showEdit"
                                :localdata="tyfsList"
                                placeholder="请选择托运方式"
                            ></uni-data-select>
                        </uni-forms-item>
                    </uni-col>
                </uni-row>

                <uni-row class="form_row">
                    <uni-col class="form_item" :span="24">
                        <uni-forms-item class="form_input" label="托运地址:" name="shaddr">
                            <input type="text" v-model="formData.shaddr" :disabled="showEdit" placeholder="请输入托运地址" />
                        </uni-forms-item>
                    </uni-col>
                </uni-row>

                <!-- <uni-row class="form_row">
                    <uni-col class="form_item" :span="16">
                        <uni-forms-item class="form_input" label="运号:" name="yunhao">
                            <input type="text" v-model="formData.yunhao" placeholder="请输入运号" />
                        </uni-forms-item>
                    </uni-col>
                </uni-row> -->

                <uni-row class="form_row">
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="业务员:" name="ywy">
                            <input type="text" v-model="formData.ywy" :disabled="showEdit" placeholder="请输入业务员" />
                        </uni-forms-item>
                    </uni-col>

                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="制单人:" name="zhuser">
                            <input type="text" v-model="formData.zhuser" :disabled="showEdit" placeholder="请输入制单人" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="附件:" name="attach">
                            <button :disabled="showEdit" v-if="!formData.attach" @click="updateImg">添加图片</button>
                            <view v-if="formData.attach" class="img_box">
                                <image style="width: 100%; height: 100%;" :src="formData.attach" />
                                <text :disabled="showEdit" @click="formData.attach = ''" class="iconfont icon-jian1"></text>
                            </view>
                        </uni-forms-item>
                    </uni-col>
                </uni-row>
                <uni-row class="form_row">
                    <uni-col class="form_item" :span="18">
                        <uni-forms-item class="form_input" label="备注:" name="remark">
                            <input type="text" v-model="formData.remark" placeholder="请输入备注" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="6">
                        <button class="btn_sub" hover-class="hover_sub" v-if="!showEdit" :disabled="subDisabled" @click="submitForm">保存</button>
                    </uni-col>
                </uni-row>

                <view style="background: #f5f5f5; padding: 10rpx 0;">
                    <view style="background: #fff; padding: 10rpx 20rpx;">
                        <uni-row class="form_row form_row_bottom">
                            <uni-col class="form_item" :span="8">
                                <view class="form_box">
                                    <view class="label">客户：</view>
                                    <input type="text" disabled v-model="formData.khname" />
                                </view>
                            </uni-col>

                            <uni-col class="form_item" :span="8">
                                <view class="form_box">
                                    <view class="label">前欠款：</view>
                                    <input type="text" disabled v-model="formData.qqk" />
                                </view>
                            </uni-col>

                            <uni-col class="form_item" :span="8">
                            </uni-col>
                        </uni-row>
                        <uni-row class="form_row form_row_bottom">
                            <uni-col class="form_item" :span="8">
                                <view class="form_box">
                                    <view class="label">本次收款：</view>
                                    <input style="color: #ff9e31;" type="number" :disabled="showEdit" v-model="formData.amount" />
                                </view>
                            </uni-col>

                            <uni-col class="form_item" :span="8">
                                <view class="form_box">
                                    <view class="label">优惠金额：</view>
                                    <input style="color: #ff9e31;" type="number" :disabled="showEdit" v-model="formData.discount" />
                                </view>
                            </uni-col>

                            <uni-col class="form_item" :span="8">
                                <view class="form_box">
                                    <view class="label">付款方式：</view>
                                    <!-- <input type="text" v-model="formData.fkfs" /> -->
                                    <uni-data-select
                                        class="form_input"
                                        v-model="formData.lkfs"
                                        :localdata="skfsList"
                                        placeholder="请选择付款方式"
                                    ></uni-data-select>
                                </view>
                            </uni-col>
                        </uni-row>

                        <uni-row class="form_row form_row_bottom">
                            <uni-col class="form_item" :span="12">
                                <view class="form_box">
                                    <view class="label">下单明细：</view>
                                    <input style="color: #ff9e31;" type="text" disabled v-model="formData.xdmx" />
                                </view>
                            </uni-col>

                            <uni-col class="form_item" :span="12">
                                <view class="form_box">
                                    <view class="label">本单总金额：</view>
                                    <input style="color: #ff9e31;" type="text" disabled v-model="formData.sum_je" />
                                </view>
                            </uni-col>
                           
                        </uni-row>
                    </view>
                </view>

            </uni-forms>
            
            <!-- <view class="form_footer"></view> -->
        </view>

        <view style="flex: 1; overflow: auto;">
            <view class="billing_header">
                <scroll-view style="height: 100%;" scroll-y="true">
                    <view class="billing_item" v-for="(item, index) in billingList" :key="index">

                        <view class="billing_info">
                            <view class="billing_img" v-if="false">
                                <image style="height: 100%; width: 100%;"  src="../../static//login/14.jpg"/>
                            </view>

                            <view class="info_center">
                                <view class="info_center_row">
                                    <view style="width: 33%;">货号: {{ item.main.huohaoname }}</view>
                                    <view style="width: 67%;">品名: {{ item.main.pm }}</view>
                                </view>

                                <view class="info_center_row">
                                    <view style="width: 33%;">单价: {{ item.main.xsprice }}</view>
                                    <view style="width: 33%;">数量: {{ item.hjsl }}</view>
                                    <view style="width: 34%;">合计价格: ￥ {{ item.hjPrice }}</view>
                                </view>
                            </view>

                            <view  @click="handleNegated(item)" style="display: flex; align-items: flex-end;">
                                {{ !item.showTable ? '查看详情 >>' : '收起 >>' }}
                            </view>
                        </view>

                        <view v-if="item.showTable" style="padding-top: 20rpx;">
                            <!--  -->

                            <view @click="handleItem(item)">
                                <uni-table border stripe emptyText="暂无更多数据"  >
                                    <uni-tr>
                                        <uni-th  width="110" align="center">颜色/尺码</uni-th>
                                        <uni-th align="center" v-for="(j, i) in item.colorTable[0].chima" :key="i">
                                            {{ i }}
                                        </uni-th>
                                    </uni-tr>
                                    <uni-tr v-for="(x, y) in item.colorTable" :key="y">
                                        <uni-td align="center" v-if="x.hj != 0">{{ x.color }}</uni-td>
                                        <uni-td align="center" v-if="x.hj != 0" v-for="(w, v) in x.chima" :key="v"> 
                                            {{ w }}
                                        </uni-td>
                                    </uni-tr>

                                </uni-table>
                            </view>
                            <!--  -->
                        </view>
                    </view>
                </scroll-view>
            </view>
            <!--  -->
        </view>

        <!-- 弹出购物组件 -->
        <addGoods
            ref="addGoodsChild"
            @childAddGoods="childAddGoods"
            ></addGoods>
	</view>
</template>

<script>
import billingTableDetail from "@/components/billing-table-detail/billing-table-detail.vue";
import addGoods from '@/components/add-goods/add-goods.vue'; // 引入自定义组件
import utils from "@/utils/utils.js";
import Http from '@/service/api'
	export default {
		components: {
            billingTableDetail,
            addGoods,
		},
		data() {
			return {
                dk: uni.getStorageSync('baseUrl'),
                moreRange: [],
                formData: {
                    attach: ''
                },
                billingList: [],

                showEdit: true, // 是否可以修改
                tyfsList: [],
                skfsList: [],
                subDisabled: false,
               
			}
		},
        computed: {},
		onLoad(r) {
            console.log('== dh ', r)
            this.GetSalesOrderDdMx(r.dh)
            this.GetBaseInfoList()
           
		},
		methods: {
            updateImg() {
                uni.chooseImage({
                    count: 1, // 最多选择1张图片
                    success: (res) => {
                        console.log('== tempFilePaths ', res.tempFilePaths )
                        this.formData.attach = res.tempFilePaths[0]
                    },
                });
            },
            submitForm() {
                let param = {
                    ...this.formData,
                    xdHuohaoDetail: {
                        data: this.billingList,
                    }
                }
                console.log('== param ', param)

                this.subDisabled = true

                Http.GetOrderDdMx(JSON.stringify(param)).then(r => {
                    console.log('== r 保存 ', r)
                    let ModulePrimaryKey = r // XS250100002

                    uni.showToast({
                        title:'修改成功',
                        icon:'none',
                        duration:2000
                    })

                    let param1 = {
                        Module: '销售订单附件上传',
                        ModulePrimaryKey,
                        sort: 0,
                        IsMain: 1,
                        customId: uni.getStorageSync('customId'),
                    }

                    console.log('== 图片 ', param1)
                    console.log('== img ', this.formData.attach)

                    if (!this.formData.attach) {
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: 1
                            });
                            let c = this.clearCart(list, this.billingList)
                            this.addCart_x(c)
                        }, 2000)
                        return
                    }

                    uni.uploadFile({
                        url: `https://${this.dk}/BaseInfo/SysHuohao/UploadAdd.aspx`,
                        filePath: this.formData.attach, //从调用页面传入 --path: imgbox, 选取图片的地址数组  
                        name: 'img',
                        formData: {
                            Module: '销售订单附件上传',
                            ModulePrimaryKey,
                            sort: 0,
                            IsMain: 1,
                            customId: uni.getStorageSync('customId'),
                        },
                        header: {
                            "Content-Type": "multipart/form-data",
                            "Authorization": 'Bearer ' + uni.getStorageSync('token'),
                        },
                        success: (r) => {
                            console.log('== img r ', r)
                            if (r.statusCode == 200) {
                                console.log('== img r.data ', r.data)
                                let data = JSON.parse(r.data)
                                console.log('== data ---- ', data)
                                    uni.showToast({
                                        title:'图片上传成功',
                                        icon:'none',
                                        duration:3000
                                    })
                                    setTimeout(() => {
                                        uni.navigateBack({
                                            delta: 1
                                        });
                                    }, 2000)
                                    let c = this.clearCart(list, this.billingList)
                                    this.addCart_x(c)
                            }
                            
                        },
                        fail: (err) => {
                            console.log('== img err ', err)
                            this.subDisabled = false
                            uni.showToast({
                                title:'图片上传失败',
                                icon:'none',
                                duration:3000
                            })
                        }
                    })

                }).catch(err => {
                    uni.showToast({
						title:err.message,
						icon:'none',
						duration:3000
					})
                    this.subDisabled = false
                })

                
            },

            handleAudit() {
                console.log('== 审核')
                this.formData.state = 1
                this.submitForm()
            },
            changeMore(e) {
                if (e == '修改') {
                    this.showEdit = false
                } else if (e == '反审') {
                    this.formData.state = 0
                    this.submitForm()
                } else if (e == '作废') {
                    this.formData.state = 2
                    this.submitForm()
                }
            },
            GetSalesOrderDdMx(dh) {
                Http.GetSalesOrderDdMx({ dh }).then(r => {
                    console.log('== r ', r)
                    this.formData = r
                    this.GetKhqkInfo(r.khid)

                    this.billingList = this.filterCheckFn(r.xdHuohaoDetail.data)

                    console.log('== 22 ', r.xdHuohaoDetail.data)
                    console.log('== billingList ', this.billingList )

                    if (r.state == 1) {
                        this.moreRange = [
                            { value: '反审', text: '反审' },
                            { value: '作废', text: '作废' },
                        ]
                    } else if (r.state == 0) {
                        this.moreRange = [
                            { value: '修改', text: '修改' },
                            { value: '作废', text: '作废' },
                        ]
                    }
                    
                }).catch(err => {
                    console.log('== err ', err)
                    uni.showToast({
						title: err.message,
						icon: 'none'
					});
                })
            },
            // 获取基础数据
            GetBaseInfoList() {
                let param = { param: 'tyfs,skfs' }
                Http.GetBaseInfoList(param).then(r => {
                   console.log('== 11 基础数据 ', r)
                   this.tyfsList = r.tyfs.map(i => ({...i, value: i.name, text: i.name}))
                   this.skfsList = r.skfs.map(i => ({...i, value: i.bh, text: i.name}))
                   
                }).catch(err => {
                    console.log('== err ', err)
                })
            },

            handleNegated(item) {
                this.billingList = this.billingList.map(i => ({
                    ...i,
                    showTable: i.main.huohao == item.main.huohao ? !i.showTable : i.showTable
                }))
            },
            GetKhqkInfo(bh) {
                Http.GetKhqkInfo({khbh: bh}).then(r => {
					this.formData = {
						...this.formData,
						qqk: r.qkje
					}
				}).catch( err => {
					console.log('= err', err)
				})
            },

            handleItem(item) {
                if (this.showEdit) return
                this.$refs.addGoodsChild.changeNum(item)
            },
            // 子传父 保存的数据
            childAddGoods(param) {
                console.log('== 修改订单 ', param)
                this.$refs.addGoodsChild.closeDrawer()

                let billingList = JSON.parse(JSON.stringify(this.billingList))
                let list = this.updateArray(billingList, param)
                this.billingList = list
            },
            // 修改数据 
            updateArray(arr, obj) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].main.huohao === obj.main.huohao) {
                        arr[i] = obj;
                    }
                }
                arr = arr.map(i => ({
                    ...i,
                    hjPrice: (Number(i.main.xsprice) || 0) * (Number(i.hjsl) || 0),
                    colorTable: this.transformArr(i.colorList)
                }))
                return arr;
            },

            // 筛选出选中的项
            filterCheckFn(arr) {
                arr.forEach(item => {
                    // 遍历 colorList
                    item.colorList.forEach(colorItem => {

                        colorItem.num =  colorItem.chimaList.reduce((sum, chima) => sum + chima.num, 0);
                    });
                    

                    item.colorList = item.colorList.filter(i => !i.chimaList.every(j => j.num == 0))

                    item.colorList = item.colorList.filter(i => i.chimaList.length)
                    item.showTable = true
                    item.colorTable = this.transformArr(item.colorList)

                    // 更新 hjsl（colorList 中所有 num 的总和）
                    item.hjsl = item.colorList.reduce((total, color) => total + color.num, 0);

                    // 更新 hjPrice（hjsl * xsprice）
                    item.hjPrice = item.hjsl * item.main.xsprice;
                });
                // 删除 colorList 为空的对象

                let a = arr.filter(item => item.colorList.length)
                return a;
            },
            // 将数组 转换成 table 形式
            transformArr(arr) {
                return arr.map(item => {
                    // 创建一个新的对象
                    let transformedItem = {
                        hj: item.num,  // 直接提取 num 作为 hj
                        color: item.color,
                        chima: {}  // 初始化一个空对象，用于存放尺寸和对应的数量
                    };

                    // 遍历 chimaList，并填充 transformedItem.chima
                    item.chimaList.forEach(chima => {
                        transformedItem.chima[chima.chima] = chima.num;
                    });

                    return transformedItem;
                });
            },
		}
	}
</script>

<style lang="less" scoped>
.xsdd_detail_content {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #fff;
    font-size: 16rpx;

    .xsdd_detail_form {
        padding: 15rpx 0rpx;
        border-bottom: 1rpx solid #ccc;
        background: #fff;

        .xsdd_top {
            padding: 0 20rpx;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10rpx;
            box-sizing: border-box;

            button {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 120rpx;
                background: #ffac60;
                height: 40rpx;
                color: #fff;
                margin: 0;
                margin-right: 40rpx;
            }

            .hover_btn {
                background: #e49a55;
            }
        }

        .form_row {
            width: 100%;
            padding: 0 20rpx;
            .uni-forms-item {
                align-items: center;
            }
        }

        .form_row_bottom {
            margin-bottom: 10rpx;
        }
        .form_item {
            display: flex;
            align-items: center;

            .form_box {
                display: flex;
                align-items: center;

                .label {
                    white-space: nowrap;
                }
            }

            .label {
                white-space: nowrap;
            }
            .form_input {
                flex: 1;
                
                .img_box {
                    position: relative;
                    width: 100%;
                    height: 80rpx;

                    .iconfont {
                        position: absolute;
                        top: 0;
                        left: 0;
                        color: red;
                        font-size: 30rpx;
                    }
                }

                button {
                    color: #ffac60;
                }
            }
        }

        .btn_sub {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 120rpx;
            background: #ffac60;
            color: #fff;
            margin: 0;
        }

        .hover_sub {
            background: #e49a55;
        }

        .form_footer {
            display: flex;
            align-items: center;
            font-size: 20rpx;
            border-top: 1rpx solid #ccc;
            padding-top: 10rpx;

            .footer_text {
                flex: 1;

                text {
                    color: #ffac60;
                    padding: 0 10rpx;
                }
            }

            button {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 120rpx;
                background: #ffac60;
                color: #fff;
                margin: 0;
            }
            .hover_btn {
                background: #e49a55;
            }

        }
        
    }
	
}



.billing_header {
    padding-top: 10rpx;
    .billing_item {
        margin-bottom: 20rpx;
        background: #fff;
        padding: 10rpx;

        .billing_info {
            display: flex;


            .billing_img {
                height: 90rpx;
                width: 90rpx;
            }

            .info_center {
                flex: 1;

                .info_center_row {
                    display: flex;
                    align-items: center;

                }
            }
        }

    }
}



</style>
